package com.zhentao.service.impl;

import com.zhentao.service.MediaUploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 媒体上传服务实现类（本地文件存储）
 * 由于MinIO存储空间不足，暂时改用本地存储
 */
@Service
public class MediaUploadServiceImpl implements MediaUploadService {

    @Value("${dynamic.media.upload.path}")
    private String uploadPath;

    @Value("${dynamic.media.url.prefix}")
    private String urlPrefix;

    @Override
    public String uploadDynamicMedia(MultipartFile file) {
        System.out.println("========== 本地存储上传开始 ==========");
        System.out.println("文件名: " + file.getOriginalFilename());
        System.out.println("文件大小: " + file.getSize() + " bytes");
        System.out.println("文件类型: " + file.getContentType());
        System.out.println("存储路径: " + uploadPath);
        
        try {
            // 1. 验证文件
            if (file.isEmpty()) {
                throw new RuntimeException("文件不能为空");
            }
            
            // 2. 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String suffix = getSuffix(originalFilename);
            String fileName = "dynamic_" + UUID.randomUUID().toString().replace("-", "") + suffix;
            System.out.println("生成文件名: " + fileName);
            
            // 3. 确保上传目录存在
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                boolean created = uploadDir.mkdirs();
                System.out.println("创建上传目录: " + uploadPath + ", 结果: " + created);
            }
            
            // 4. 保存文件到本地
            Path filePath = Paths.get(uploadPath, fileName);
            Files.write(filePath, file.getBytes());
            System.out.println("文件已保存到: " + filePath.toAbsolutePath());
            
            // 5. 生成访问URL
            String mediaUrl = urlPrefix + fileName;
            System.out.println("生成访问URL: " + mediaUrl);
            System.out.println("========== ✓ 上传完成 ==========");
            
            return mediaUrl;
            
        } catch (IOException e) {
            System.err.println("========== ✗ 上传失败 ==========");
            System.err.println("文件保存失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("媒体上传失败: " + e.getMessage(), e);
        } catch (Exception e) {
            System.err.println("========== ✗ 上传失败 ==========");
            System.err.println("上传失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("媒体上传失败: " + e.getMessage(), e);
        }
    }

    @Override
    public List<String> uploadDynamicMediaBatch(MultipartFile[] files) {
        System.out.println("========== 本地存储批量上传开始 ==========");
        System.out.println("文件数量: " + (files != null ? files.length : 0));
        
        List<String> urls = new ArrayList<>();
        
        if (files == null || files.length == 0) {
            return urls;
        }
        
        try {
            // 确保上传目录存在
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                boolean created = uploadDir.mkdirs();
                System.out.println("创建上传目录: " + uploadPath + ", 结果: " + created);
            }
            
            // 批量上传文件
            int index = 0;
            for (MultipartFile file : files) {
                if (file != null && !file.isEmpty()) {
                    index++;
                    System.out.println("上传文件 " + index + "/" + files.length + ": " + file.getOriginalFilename());
                    
                    try {
                        // 生成唯一文件名
                        String originalFilename = file.getOriginalFilename();
                        String suffix = getSuffix(originalFilename);
                        String fileName = "dynamic_" + UUID.randomUUID().toString().replace("-", "") + suffix;
                        
                        // 保存文件到本地
                        Path filePath = Paths.get(uploadPath, fileName);
                        Files.write(filePath, file.getBytes());
                        System.out.println("  文件已保存: " + fileName);
                        
                        // 生成访问URL
                        String mediaUrl = urlPrefix + fileName;
                        urls.add(mediaUrl);
                        
                    } catch (IOException e) {
                        System.err.println("  ✗ 文件保存失败: " + file.getOriginalFilename() + ", 错误: " + e.getMessage());
                        throw new RuntimeException("文件上传失败: " + e.getMessage(), e);
                    }
                }
            }
            
            System.out.println("========== ✓ 批量上传完成，成功: " + urls.size() + " 个文件 ==========");
            
        } catch (Exception e) {
            System.err.println("========== ✗ 批量上传失败 ==========");
            System.err.println("错误: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("批量媒体上传失败: " + e.getMessage(), e);
        }
        
        return urls;
    }

    private String getSuffix(String name) {
        if (name == null) return "";
        int i = name.lastIndexOf('.');
        return i >= 0 ? name.substring(i) : "";
    }
}


